<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

// 引入邮箱
use app\common\library\Email;

class Business extends Home
{

    // 控制器初始化
    public function _initialize()
    {
        // 调用父类构造函数（必须）
        parent::_initialize();

        $this->BusinessModel = model("Business.Business");
        $this->RegionModel = model('Region');
        $this->EmsModel = model('Ems');
        $this->CouponModel = model('Coupon.Coupon');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->FollowModel = model('Subject.Teacher.Follow');
        $this->CollectionModel = model('Business.Collection');
        $this->SubjectModel = model('Subject.Subject');
        $this->OrderModel = model('Subject.Order');
        $this->CategoryModel = model('Subject.Category');
        $this->RecordModel = model('Business.Record');
        $this->CommentModel = model('Subject.Comment');
        $this->SubjectModel = model('Subject.Subject');
        $this->PayModel = model('Pay.Pay');
    }


    // 首页
    public function index()
    {
        return $this->view->fetch();
    }

    // 基本资料
    public function profile()
    {
        if ($this->request->isPost()) {
            // 接收请求数据
            $params = $this->request->param();

            // 组装必填数据
            $data = [
                'id' => $this->Business['id'],
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender']
            ];

            // 组装选填数据
            // 邮箱
            if (!empty($params['email'])) {
                $data['email'] = $params['email'];
                $data['auth'] = '0';
            }
            // 密码
            if (!empty($params['password'])) {
                $data['salt'] = build_randstr();
                $data['password'] = md5($params['password'] . $data['salt']);
            }
            // 文件
            if ($_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                // 上传头像
                $data['avatar'] = upload('avatar');

                // 判断是否上传成功
                if (empty($data['avatar'])) {
                    $this->error('上传失败', 'home/business/profile');
                    exit;
                }
                // 删除旧头像
                $old_avatar = $this->BusinessModel->where('id', $data['id'])->value('avatar');
                if (!empty($old_avatar)) {
                    @unlink(ROOT_PATH . 'public' . DS . 'uploads' . DS . $old_avatar);
                }
            }
            // 地区
            if (isset($params['code']) && !empty($params['code'])) {
                $parentpath = $this->RegionModel->where('code', $params['code'])->value('parentpath');

                if (empty($parentpath)) {
                    $this->error('地区不存在', 'home/business/profile');
                    exit;
                }

                $path = explode(',', $parentpath);
                $data['province'] = $path[0] ?? '';
                $data['city'] = $path[1] ?? '';
                $data['district'] = $path[2] ?? '';
            }

            // 显式指定更新数据操作  需要验证场景
            $result = $this->BusinessModel->validate('common/Business/Business.edit')->isUpdate(true)->save($data);

            if ($result === false) {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 更新session
            session('business', $this->BusinessModel->where('id', $data['id'])->find());

            $this->success('更新成功', 'home/business/index');
            exit;
        }

        $this->assign('Business', $this->Business);

        return $this->view->fetch();
    }

    // 邮箱验证
    public function email()
    {
        // 验证是否已验证邮箱
        if ($this->Business['auth'] == 1) {
            $this->success('邮箱已验证', 'home/business/index');
            exit;
        }

        if ($this->request->isPost()) {
            // 获取用户输入的验证码
            $code = $this->request->param('code');
            // 验证验证码
            $emsinfo = $this->EmsModel->where('email', $this->Business['email'])->find();

            if (empty($emsinfo)) {
                $this->error('验证码不存在');
                exit;
            }

            if ($code != $emsinfo['code']) {
                $this->error('验证码错误');
                exit;
            }

            // 开启邮箱事务
            $this->BusinessModel->startTrans();
            $this->EmsModel->startTrans();
            // 验证成功，更新邮箱状态
            $Updresult = $this->BusinessModel->where('id', $this->Business['id'])->update(['auth' => 1]);
            // 删除数据库中验证码相关数据
            $DelResult = $this->EmsModel->where('email', $this->Business['email'])->delete();
            if ($Updresult === false || $DelResult === false) {
                $this->error('验证失败');
                // 回滚事务
                $this->EmsModel->rollback();
                $this->BusinessMobel->rollback();
                $this->exit;
            }
            // 提交事务
            $this->EmsModel->commit();
            $this->BusinessModel->commit();
            // 更新session
            session('business', $this->BusinessModel->where('id', $this->Business['id'])->find());

            $this->success('验证成功', 'home/business/index');
            exit;
        }


        return $this->view->fetch();
    }

    // 发送邮件 
    public function send()
    {
        if ($this->request->isPost()) {
            $emsinfo = $this->EmsModel->where('email', $this->Business['email'])->find();

            if ($emsinfo) {
                $this->success('邮件已发送，请注意查收');
                exit;
            }

            // 启动事务
            $this->EmsModel->startTrans();

            // 获取验证码
            $code = build_randstr(4);

            $EmsData = [
                'event' => 'TP云课堂邮箱认证',
                'email' => $this->Business['email'],
                'code' => $code
            ];

            $EmsStatus = $this->EmsModel->save($EmsData);

            if ($EmsStatus === false) {
                $this->error('存储验证码失败: ' . $this->EmsModel->getError());
                exit;
            }

            // 实例化一个Email对象
            $email = new Email;

            $content = "<h1>TP云课堂项目邮箱验证码: $code</h1>";

            $SendEms = $email->subject('TP云课堂邮箱认证')->to($this->Business['email'])->message($content)->send();

            if ($SendEms === false) {
                $this->error('邮件发送失败: ' . $email->getError());
                // 回滚事务
                $this->EmsModel->rollback();
                exit;
            }

            // 提交事务
            $this->EmsModel->commit();
            $this->success('发送邮件成功');
            exit;
        }
    }

    // 我的优惠券
    public function coupon()
    {
        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'intval');
            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 组装响应数据
            $data = [
                'list' => [],
                'count' => 0,
            ];

            // 查询优惠券列表
            $couponList = $this->CouponModel
                ->limit($offset, $limit)
                ->order('id desc')->select();

            // var_dump($couponList[0]['endtime']);
            // exit;

            // 获取用户信息
            $business = session('business') ? session('business') : [];

            $couponData = [];
            // 提取查询结果的data字段
            foreach ($couponList as $coupon) {

                // 判断用户是否已登录
                $result = null;
                if ($business) {
                    // 查询优惠券是否已领取
                    $result = $this->ReceiveModel
                        ->where('cid', $coupon['id'])
                        ->where('busid', $business['id'])
                        ->find();
                }
                // 组装领取状态字段，并只把该用户领取的优惠券组装入数组
                if ($result) {
                    $coupon['receive_text'] = '已领取';
                    $couponData[] = $coupon;
                } else {
                    $coupon['receive_text'] = null;
                }
            }

            // 组装数据
            if ($couponList) {
                $data['list'] = $couponData;
                $data['count'] = $this->CouponModel->count();


                // 响应数据
                $this->success('', '', $data);
            } else {
                // 响应数据
                $this->error('暂无数据', '', $data);
            }
        }

        return $this->view->fetch();
    }

    // 我的关注列表
    public function follow()
    {
        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'intval');

            // 获取搜索关键字
            $keywords = $this->request->param('keywords', '', 'trim');

            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 组装响应数据
            $data = [
                'list' => [],
                'count' => 0,
            ];

            // 查询关注列表
            $followList = $this->FollowModel
                ->where('busid', $this->Business['id'])
                ->with(['teacher' => function ($qurey) use ($keywords) {
                    if ($keywords) {
                        $qurey->where('name', 'like', "%{$keywords}%");
                    }
                }])
                ->limit($offset, $limit)
                ->select();

            // 组装数据
            if ($followList) {
                $data['list'] = $followList;
                $data['count'] = $this->FollowModel->count();


                // 响应数据
                $this->success('', '', $data);
            } else {
                // 响应数据
                $this->error('暂无数据', '', $data);
            }
        }

        return $this->view->fetch();
    }

    // 我的收藏列表
    public function collection()
    {
        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'intval');

            // 获取搜索关键字
            $keywords = $this->request->param('keywords', '', 'trim');

            $where = [];

            // 获取用户id，查询用户收藏表
            $collectionList = $this->CollectionModel
                ->where([
                    'busid' => $this->Business['id'],
                    'status' => 'subject'
                ])
                ->select();
            // 获取课程收藏id列表
            $collectionIdList = [];
            foreach ($collectionList as $item) {
                $collectionIdList[] = $item['collectid'];
            }
            // var_dump($collectionIdList);exit;
            // 组装查询条件
            $where['fa_subject.id'] = ['IN', $collectionIdList];

            // 搜索框查询条件
            if ($keywords) {
                $where['title'] = ['like', "%{$keywords}%"];
            }

            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 组装响应数据
            $data = [
                'list' => [],
                'count' => 0,
            ];

            // 查询课程列表
            $subjectList = $this->SubjectModel
                ->where($where)
                ->limit($offset, $limit)
                ->with(['category', 'teacher'])
                ->order('id desc')
                ->select();

            // 组装数据
            if ($subjectList) {
                $data['list'] = $subjectList;
                $data['count'] = $this->SubjectModel->count();

                // 响应数据
                $this->success('', '', $data);
            } else {
                // 响应数据
                $this->error('暂无数据', '', $data);
            }
        }

        return $this->view->fetch();
    }

    // 我的课程列表
    public function subject()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');

            $where = [
                'busid' => $this->Business['id']
            ];

            if (!empty($keywords)) {
                $where['subject.title'] = ['like', "%$keywords%"];
            }


            $list = $this->OrderModel->with(['subject'])->where($where)->page("$page, 10")->order('createtime desc')->select();

            // 总数
            $count = $this->OrderModel->with(['subject'])->where($where)->count();

            if ($list) {

                foreach ($list as $item) {
                    $cateid = isset($item['subject']['cateid']) ? trim($item['subject']['cateid']) : 0;
                    $name = $this->CategoryModel->where('id', $cateid)->value('name');
                    $item['category'] = $name ? $name : '未知分类';

                    $comment = $this->CommentModel->where('orderid', $item['id'])->find();
                    $item['comment_status'] = $comment ? true : false;
                }

                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
        return $this->view->fetch();
    }

    // 团队成员列表
    public function team()
    {
        // 获取当前用户信息
        $Business = $this->Business;

        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'trim');
            // 获取查询关键词
            $keywords = $this->request->param('keywords', '', 'trim');

            // 组装查询条件
            $where = [
                'parentid' => $Business['id']
            ];

            if (!empty($keywords)) {
                $where['nickname|mobile'] = ['like', "%$keywords%"];
            }

            // 查询团队成员列表
            $list = $this->BusinessModel->where($where)->page("$page, 10")->order('id desc')->select();

            // 总数
            $count = $this->BusinessModel->where($where)->count();

            if ($list) {
                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }

        return $this->view->fetch();
    }

    // 消费订单列表
    public function record()
    {
        // 获取当前用户信息
        $Business = $this->Business;

        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'trim');
            // 获取查询关键词
            $keywords = $this->request->param('keywords', '', 'trim');

            // 组装查询条件
            $where = [
                'busid' => $Business['id']
            ];

            if (!empty($keywords)) {
                $where['content'] = ['like', "%$keywords%"];
            }

            // 查询团队成员列表
            $list = $this->RecordModel->where($where)->page("$page, 10")->order('id desc')->select();

            // 总数
            $count = $this->RecordModel->where($where)->count();

            if ($list) {
                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }

        return $this->view->fetch();
    }

    // 课程评价
    public function comment()
    {
        // 获取订单id
        $orderid = $this->request->param('orderid', 0, 'trim');

        // 查询订单信息
        $orderinfo = $this->OrderModel->with('subject')->find($orderid);

        if (!$orderinfo) {
            $this->error('订单不存在');
            exit;
        }

        // 查询是否已评论
        $comment = $this->CommentModel->where('orderid', $orderid)->find();

        // 组装订单信息
        $orderinfo['comment'] = [
            'id' => $comment ? $comment['id'] : 0,
            'rate' => $comment ? $comment['rate'] : '',
            'content' => $comment ? $comment['content'] : '',
        ];

        if ($this->request->isPost()) {
            // 获取评价内容
            $content = $this->request->param('content', '', 'trim');
            // 获取评分
            $rate = $this->request->param('rate', '', 'trim');

            // 组装评价数据
            $data = [
                'content' => $content,
                'busid' => $this->Business['id'],
                'subid' => $orderinfo['subid'],
                'rate' => $rate,
                'orderid' => $orderid
            ];

            // 保存评价信息
            $result = $this->CommentModel->save($data);

            if ($result === false) {
                $this->error($this->CommentModel->getError());
                exit;
            } else {
                $this->success('评价成功', 'home/business/subject');
                exit;
            }
        }

        $this->assign('orderinfo', $orderinfo);

        return $this->view->fetch();
    }

    // 课程评价列表
    public function commentIndex()
    {
        // 查询评论表全部信息
        $commentList = $this->CommentModel->with([
            'business',
            'subject'
        ])->order('rate')->select();

        // 赋值变量
        $this->assign('commentList', $commentList);

        return $this->view->fetch();
    }

    // 关于我们
    public function contact()
    {
        $subjectlist = $this->SubjectModel->order('createtime desc')->limit(6)->select();

        $configinfo = [
            'sales' => config('site.sales') ? config('site.sales') : '',
            'technical' => config('site.technical') ? config('site.technical') : '',
            'service' => config('site.service') ? config('site.service') : '',
        ];

        $this->assign([
            'subjectlist' => $subjectlist,
            'configinfo' => $configinfo
        ]);

        return $this->view->fetch();
    }

    // 充值
    public function pay()
    {
        $action = $this->request->param('action', '', 'trim');

        if($this->request->isPost())
        {
            $type = $this->request->param('type', 'zfb', 'trim');
            $money = $this->request->param('money', '0', 'trim');

            if($money <= 0)
            {
                $this->error(__('充值金额不能小于0'));
                exit;
            }

            // 携带一个自定义的参数过去
            $third = ['busid' => $this->Business['id']];

            //开始调用支付(组装参数)
            $data = [
                'name' => '余额充值', //标题
                'third' => $third, //传递的第三方的参数
                'type' => $type, //支付方式
                'total'=> $money,//订单原价充值的价格 
                'cashier' => 1, //是否需要收银台界面
                'jump' => '/home/business/pay?action=success', //订单支付完成后跳转的界面
                'notice' =>'/home/pay/business', //异步回调地址
            ];
            
            //调用模型中的支付方法
            $result = $this->PayModel->payment($data);

            echo $result;
            exit;

        }

        if($action === 'success')
        {
            $this->success('充值成功', 'home/business/index');
            exit;
        }

        return $this->view->fetch();
    }
}
